/*
* @author dumeng
* desc 导出文件 关键信息脱敏验证+短信验证
*/
'use strict'
import request from '@/utils/request'
import {
  MessageBox,
  Loading,
  Message
} from 'element-ui'
import { exportSign } from '@/utils/fileImportOrExportSign'

/**
 *
 * @param moduleName 模块名称
 * @param actId  活动id  没有活动id 传''
 * @param maskAPI  脱敏导出的方法
 * @param noMaskAPI  非脱敏导出的方法
 * @param params   已经加过签名的参数
 * @param fileName 导出文件名称
 */
export function exportCheck(moduleName = '', actId = '', maskAPI = function() {
}, noMaskAPI = function() {
}, params = {}, fileName = '') {
  new Promise((resolve, reject) => {
    if (!moduleName) {
      Message({
        message: '模块名为空',
        type: 'warning'
      })
      return
    }
    if (!params['ttsxbwqm']) {
      params = exportSign(params).obj
    }
    fileName = fileName || '记录.xlsx'

    let loadingInstance = Loading.service({ spinner: 'el-icon-loading', text: '请稍后' })
    request({
      baseURL: '/API-ENTERPRISE-BACKEND/',
      url: 'backend/sysDesensitizationConfig/getExportSetting',
      method: 'post',
      data: {
        model: moduleName,
        dataId: actId
      }
    }).then(res => {
      loadingInstance.close()
      let msg = ''
      if (res.data) {
        // 如果手机号与证件号码都可以不脱敏导出
        if (res.data.data.phoneNum === '2' && res.data.data.idNo === '2') {
          msg = `是否对数据脱敏?`
          // 如果手机号可以不脱敏，证件号码脱敏
        } else if (res.data.data.phoneNum === '2') {
          msg = `是否对数据脱敏? <br> <span style="color: red;">注意：证件号码必须脱敏！</span>`
          // 如果手机号可以不脱敏，证件号码必须脱敏
        } else if (res.data.data.idNo === '2') {
          msg = `是否对数据脱敏?<br> <span style="color: red;">注意：手机号码必须脱敏！</span>`
        } else {
          msg = `是否对数据脱敏?<br> <span style="color: red;">注意：手机号与证件号码都必须脱敏！<br>（如需导出非脱敏数据，请联系管理员）</span>`
        }
      } else {
        msg = `是否对数据脱敏?<br>  <span style="color: red;">注意：手机号与证件号码都必须脱敏！<br>（如需导出非脱敏数据，请联系管理员）</span>`
      }
      MessageBox.confirm(msg, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
        distinguishCancelAndClose: true,
        dangerouslyUseHTMLString: true,
        showCancelButton: res.data.data.phoneNum === '2' || res.data.data.idNo === '2'
      }).then(() => {
        loadingInstance = Loading.service({ spinner: 'el-icon-loading', text: '请稍后' })
        maskAPI(params).then(async(res) => {
          loadingInstance.close()
          const content = res.data
          const blob = new Blob([content])
          try {
            const a = await blob.text()
            const obj = JSON.parse(a)
            if (obj.code && obj.msg) {
              Message({
                message: obj.msg,
                type: 'error'
              })
              return
            }
          } catch (e) {
          }
          if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else {
            navigator.msSaveBlob(blob, fileName)
          }
        }).catch(error => {
          loadingInstance.close()
          if (!error.msg) {
            Message({
              message: error,
              type: 'error'
            })
          }
        })
      }).catch((action) => {
        if (action === 'cancel') {
          loadingInstance = Loading.service({ spinner: 'el-icon-loading', text: '请稍后' })
          noMaskAPI(params).then(async(res) => {
            loadingInstance.close()
            const content = res.data
            const blob = new Blob([content])
            try {
              const a = await blob.text()
              const obj = JSON.parse(a)
              if (obj.code && obj.msg) {
                Message({
                  message: obj.msg,
                  type: 'error'
                })
                return
              }
            } catch (e) {
            }
            if ('download' in document.createElement('a')) {
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else {
              navigator.msSaveBlob(blob, fileName)
            }
          }).catch(error => {
            if (!error.msg) {
              Message({
                message: error,
                type: 'error'
              })
            }
            loadingInstance.close()
          })
        }
      })
    }).catch(error => {
      loadingInstance.close()
      console.log(error)
      Message({
        message: error,
        type: 'error'
      })
    })
  })
}

